	package mwn.droidbus.connection;

	import java.io.IOException;
	import java.io.InputStreamReader;
	import java.net.URI;
	import java.util.ArrayList;
	import java.io.*;
	
	import mwn.droidbus.elements.Bus;
	import mwn.droidbus.elements.BusStop;
	import mwn.droidbus.elements.Route;

	import org.apache.http.HttpResponse;
	import org.apache.http.client.HttpClient;
	import org.apache.http.client.methods.HttpGet;
	import org.apache.http.impl.client.DefaultHttpClient;

	import com.google.android.maps.GeoPoint;

	import android.util.Log;	

	public class Connection implements InformationUpdater {
		
		final String SERVER_ADDRESS = "http://118.210.157.38:8080/MWN/MWN";
		
		public static void main(String[] args) {
			System.out.println("test");
		}
		
		public String removeHtmlTag(String s) {
			s = s.replaceAll("\\<[^>]*>","").trim();
			s = s.replaceAll("&nbsp;", "");
			return s;
		}	
		
		private Bus getBus(String text) {
			//Log.d("debug","text:" + text);
			String[] list = text.split(" ");
			String id = list[0];
			String routeID = list[0];
			double latitude = Double.parseDouble(list[1].substring(2,list[1].length()));
			double longitude = Double.parseDouble(list[2].substring(2,list[2].length()));
			Bus bus = new Bus(id + latitude/2, routeID, latitude,longitude,0.0 );
			return bus;
		}		
		
		public ArrayList<Bus> getUserDefinesBusses(String routeId) throws Exception {
			  BufferedReader in = null;
			  StringBuffer sb = new StringBuffer("");
			  ArrayList<Bus> buses = new ArrayList<Bus>();
			  String page = "";
			  try {
				  HttpClient client = new DefaultHttpClient();
				  HttpGet request = new HttpGet();
				  //request.setURI(new URI("http://121.45.122.23:8080/MWN/MWN"));
				  //request.setURI(new URI("http://129.127.203.40:8080/Server/MWN"));
				  request.setURI(new URI(SERVER_ADDRESS));
				  
				  HttpResponse response = client.execute(request);
				  in = new BufferedReader
				  (new InputStreamReader(response.getEntity().getContent()));          
				  String line = "";
				  String NL = System.getProperty("line.separator");
				  while ((line = in.readLine()) != null) {       	

					  if(line.contains("X")) {
						  page = removeHtmlTag(line);
						  Bus bus = getBus(page);
						  if(bus.getRouteID() == routeId) {
							  buses.add(bus);
						  }
					  }
				  }
				  in.close();
				  } catch (Exception e) {
						// TODO: handle exception
					  e.printStackTrace();
					}
				finally {
				  if (in != null) {
					  try {
						  in.close();
						  } catch (IOException e) {
						  e.printStackTrace();
					  }
				  }
				  return buses;
			  }		
			}	

		public ArrayList<Bus> getCurrentLocationAllBusses() throws Exception {
			//Log.d("debug", "Get current location all busses called");
		  BufferedReader in = null;
		  StringBuffer sb = new StringBuffer("");
		  ArrayList<Bus> buses = new ArrayList<Bus>();
		  String page = "";
		  try {
			  HttpClient client = new DefaultHttpClient();
			  HttpGet request = new HttpGet();
			  request.setURI(new URI(SERVER_ADDRESS));
			  HttpResponse response = client.execute(request);
			  in = new BufferedReader
			  (new InputStreamReader(response.getEntity().getContent()));          
			  String line = "";
			  String NL = System.getProperty("line.separator");
			  while ((line = in.readLine()) != null) {       	

				  if(line.contains("X")) {
					  page = removeHtmlTag(line);
					  Bus bus = getBus(page);
					  buses.add(bus);
				  }
			  }
			  in.close();
			  } catch (Exception e) {
					// TODO: handle exception
				  e.printStackTrace();
				  //Log.d("debug", "Exception e:" + e.toString());
				}
			finally {
			  if (in != null) {
				  try {
					  in.close();
					  } catch (IOException e) {
					  e.printStackTrace();
				  }
			  }
			  return buses;
		  }		
		}

		@Override
		public ArrayList<Route> getRoutes() throws Exception {
			BufferedReader in = null;
			  StringBuffer sb = new StringBuffer("");
			  ArrayList<Route> routes = new ArrayList<Route>();
			  String page = "";
			  try {
				  HttpClient client = new DefaultHttpClient();
				  //request.setURI(new URI("http://121.45.122.23:8080/MWN/MWN"));
				  HttpGet request = new HttpGet();
				  request.setURI(new URI(SERVER_ADDRESS + "?routes=yes"));
				  HttpResponse response = client.execute(request);
				  in = new BufferedReader
				  (new InputStreamReader(response.getEntity().getContent()));          
				  String line = "";
					
					// 0 : New route 1 : Stops 2 : route
					int temp = 0;			
					Route newRoute = null;
					while((line = in.readLine()) != null) {
						//Log.d("debug","line: " + line);
						line = removeHtmlTag(line);
						if(line.length() != 0) {
							if(line.contains("ROUTE:") && !(line.length() == 6)) {
								if(newRoute != null) routes.add(newRoute);
								temp = 1;
								newRoute = new Route(line.substring(6,line.length())); 
								//Log.d("debug","new route : " + line.substring(6,line.length()));
							} else {
								if(line.contains("Stops")) temp = 2;
								if(line.contains("Route")) temp = 3;
							}
							
							if(temp == 2) {
								if((newRoute != null) && (!line.contains("Stops"))) {
									String[] list = line.split(",");
									String stopId = list[2];
									double latitude = Double.parseDouble(list[0]);
									double longitude = Double.parseDouble(list[1]);
									BusStop newBusStop = new BusStop(stopId,"", latitude, longitude);
									newRoute.addStop(newBusStop);
								}				
							}
							
							if(temp == 3) {
								if((newRoute != null) && (!line.contains("Route"))) {
									String[] list = line.split(",");
									double latitude = Double.parseDouble(list[0]);
									double longtitude = Double.parseDouble(list[1]);
									newRoute.addPathPoint(latitude, longtitude);
								}
							}
						}
						
					}
					routes.add(newRoute);
				  in.close();
				  //page = sb.toString();
				  } catch (Exception e) {
						// TODO: handle exception
					  e.printStackTrace();
					  Log.d("debug", "Exception e:" + e.toString());
					}
				finally {
				  if (in != null) {
					  try {
						  in.close();
						  } catch (IOException e) {
						  e.printStackTrace();
					  }
				  }
				  return routes;
			  }	
		}

		@Override
		public ArrayList<BusStop> getStops() throws Exception {
			// TODO Auto-generated method stub
			return new ArrayList<BusStop>();
		}	
	}
